<template>
  <view class="activity-container">
    <!-- 搜索筛选栏 -->
    <SearchFilter 
      @search="handleAdvancedSearch"
      @reset="handleSearchReset"
      ref="searchFilterRef"
    />

    <!-- 活动列表 -->
    <scroll-view 
      class="activity-list" 
      scroll-y 
      @scrolltolower="loadMore"
      refresher-enabled
      :refresher-triggered="refreshing"
      @refresherrefresh="onRefresh"
    >
      <view class="list-content">
        <view 
          class="activity-card"
          v-for="activity in activityList"
          :key="activity.id"
          @click="viewDetail(activity)"
        >
          <view class="card-header">
            <image 
              class="activity-image" 
              :src="activity.image || '/static/images/default-activity.png'"
              mode="aspectFill"
            />
            <view class="activity-info">
              <text class="activity-name">{{ activity.name }}</text>
              <text class="activity-desc">{{ activity.description }}</text>
              <view class="price-info">
                <text class="original-price">¥{{ formatPrice(activity.original_price) }}</text>
                <text class="group-price">¥{{ formatPrice(activity.group_price) }}</text>
              </view>
            </view>
            <view class="activity-status">
              <uni-tag 
                :text="getStatusText(activity)" 
                :type="getStatusType(activity)"
                size="small"
              />
            </view>
          </view>
          
          <view class="card-body">
            <view class="activity-meta">
              <view class="meta-item">
                <uni-icons type="person" size="14" color="#999" />
                <text class="meta-text">{{ activity.min_members }}{{ activity.max_members ? `-${activity.max_members}` : '' }}人成团</text>
              </view>
              <view class="meta-item">
                <uni-icons type="clock" size="14" color="#999" />
                <text class="meta-text">{{ activity.deductible_hours }}小时</text>
              </view>
              <view class="meta-item">
                <uni-icons type="shop" size="14" color="#999" />
                <text class="meta-text">{{ activity.applicable_stores?.length || 0 }}个门店</text>
              </view>
            </view>
            
            <view class="time-info">
              <text class="time-label">活动时间：</text>
              <text class="time-text">{{ formatTime(activity.start_time) }} - {{ formatTime(activity.end_time) }}</text>
            </view>
          </view>

          <view class="card-actions">
            <button class="action-btn secondary" @click.stop="editActivity(activity)">
              <uni-icons type="compose" size="16" />
              <text>编辑</text>
            </button>
            <button class="action-btn primary" @click.stop="viewDetail(activity)">
              <uni-icons type="eye" size="16" />
              <text>详情</text>
            </button>
            <button 
              class="action-btn" 
              :class="activity.status === 1 ? 'warning' : 'success'"
              @click.stop="toggleActivityStatus(activity)"
            >
              <uni-icons :type="activity.status === 1 ? 'minus' : 'checkmarkempty'" size="16" />
              <text>{{ activity.status === 1 ? '禁用' : '启用' }}</text>
            </button>
            <button class="action-btn danger" @click.stop="deleteActivity(activity)">
              <uni-icons type="trash" size="16" />
              <text>删除</text>
            </button>
          </view>
        </view>

        <!-- 加载更多 -->
        <view class="load-more" v-if="hasMore">
          <uni-load-more :status="loadStatus" />
        </view>

        <!-- 空状态 -->
        <view class="empty-state" v-if="!loading && activityList.length === 0">
          <image class="empty-image" src="/static/images/empty-activity.png" />
          <text class="empty-text">暂无团购活动</text>
          <button class="empty-btn" @click="createActivity">创建活动</button>
        </view>
      </view>
    </scroll-view>

    <!-- 浮动操作按钮 -->
    <view class="fab" @click="createActivity">
      <uni-icons type="plus" size="24" color="#fff" />
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue';
import { activityApi } from '@/api/groupbuy';
import type { Activity, ActivityQuery } from '@/types/groupbuy';
import SearchFilter from './components/SearchFilter.vue';

// 响应式数据
const activityList = ref<Activity[]>([]);
const loading = ref(false);
const refreshing = ref(false);
const currentPage = ref(1);
const pageSize = ref(10);
const hasMore = ref(true);
const searchParams = ref<any>({});
const searchFilterRef = ref();

// 加载状态
const loadStatus = computed(() => {
  if (loading.value) return 'loading';
  if (!hasMore.value) return 'noMore';
  return 'more';
});

// 格式化价格
const formatPrice = (price: number) => {
  return (price / 100).toFixed(2);
};

// 格式化时间
const formatTime = (timestamp: number) => {
  const date = new Date(timestamp * 1000);
  return `${date.getMonth() + 1}/${date.getDate()} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
};

// 获取状态文本
const getStatusText = (activity: Activity) => {
  const now = Date.now() / 1000;
  if (activity.status === 0) return '已禁用';
  if (now < activity.start_time) return '未开始';
  if (now > activity.end_time) return '已结束';
  return '进行中';
};

// 获取状态类型
const getStatusType = (activity: Activity) => {
  const now = Date.now() / 1000;
  if (activity.status === 0) return 'error';
  if (now < activity.start_time) return 'warning';
  if (now > activity.end_time) return 'info';
  return 'success';
};

// 加载活动列表
const loadActivityList = async (reset = false) => {
  if (loading.value) return;
  
  try {
    loading.value = true;
    
    if (reset) {
      currentPage.value = 1;
      hasMore.value = true;
    }

    const params: ActivityQuery = {
      page: currentPage.value,
      pageSize: pageSize.value,
      ...searchParams.value, // 合并搜索参数
    };

    const res = await activityApi.getList(params);
    
    if (res) {
      const newList = res.list || [];
      
      // 根据搜索参数中的状态筛选进行前端过滤
      let filteredList = newList;
      if (searchParams.value.status && searchParams.value.status !== 'all') {
        const now = Date.now() / 1000;
        filteredList = newList.filter(activity => {
          switch (searchParams.value.status) {
            case 'active':
              return activity.status === 1 && now >= activity.start_time && now <= activity.end_time;
            case 'pending':
              return activity.status === 1 && now < activity.start_time;
            case 'ended':
              return activity.status === 1 && now > activity.end_time;
            case 'disabled':
              return activity.status === 0;
            default:
              return true;
          }
        });
      }
      
      if (reset) {
        activityList.value = filteredList;
      } else {
        activityList.value.push(...filteredList);
      }
      
      hasMore.value = newList.length === pageSize.value;
      
      if (!reset) {
        currentPage.value++;
      }
    }
  } catch (error) {
    console.error('加载活动列表失败:', error);
    uni.showToast({
      title: '加载失败',
      icon: 'none',
    });
  } finally {
    loading.value = false;
    refreshing.value = false;
  }
};

// 高级搜索
const handleAdvancedSearch = (params: any) => {
  searchParams.value = params;
  loadActivityList(true);
};

// 搜索重置
const handleSearchReset = () => {
  searchParams.value = {};
  loadActivityList(true);
};

// 下拉刷新
const onRefresh = () => {
  refreshing.value = true;
  loadActivityList(true);
};

// 加载更多
const loadMore = () => {
  if (hasMore.value && !loading.value) {
    loadActivityList();
  }
};

// 查看详情
const viewDetail = (activity: Activity) => {
  uni.navigateTo({
    url: `/pages/groupons/activity/detail?id=${activity.id}&mode=view`,
  });
};

// 编辑活动
const editActivity = (activity: Activity) => {
  uni.navigateTo({
    url: `/pages/groupons/activity/detail?id=${activity.id}&mode=edit`,
  });
};

// 创建活动
const createActivity = () => {
  uni.navigateTo({
    url: '/pages/groupons/activity/detail?mode=create',
  });
};

// 删除活动
const deleteActivity = (activity: Activity) => {
  uni.showModal({
    title: '确认删除',
    content: `确定要删除活动"${activity.name}"吗？删除后无法恢复。`,
    success: async (result: any) => {
      if (result.confirm) {
        try {
          await activityApi.delete(activity.id);
          uni.showToast({
            title: '删除成功',
            icon: 'success',
          });
          loadActivityList(true);
        } catch (error) {
          console.error('删除失败:', error);
          uni.showToast({
            title: '删除失败',
            icon: 'none',
          });
        }
      }
    },
  });
};

// 切换活动状态
const toggleActivityStatus = async (activity: Activity) => {
  const newStatus = activity.status === 1 ? 0 : 1;
  const statusText = newStatus === 1 ? '启用' : '禁用';
  
  try {
    await activityApi.update(activity.id, { status: newStatus });
    uni.showToast({
      title: `${statusText}成功`,
      icon: 'success',
    });
    loadActivityList(true);
  } catch (error) {
    console.error('状态更新失败:', error);
    uni.showToast({
      title: `${statusText}失败`,
      icon: 'none',
    });
  }
};

// 页面加载
onMounted(() => {
  loadActivityList(true);
});
</script>

<style lang="scss" scoped>
.activity-container {
  height: 100vh;
  background: #f5f5f5;
  display: flex;
  flex-direction: column;
}

.search-section {
  background: #fff;
  padding: 24rpx 32rpx 16rpx;
  border-bottom: 1rpx solid #f0f0f0;
  
  .search-bar {
    margin-bottom: 16rpx;
  }
  
  .filter-bar {
    .filter-scroll {
      white-space: nowrap;
      
      .filter-list {
        display: flex;
        gap: 16rpx;
        
        .filter-item {
          flex-shrink: 0;
          padding: 12rpx 24rpx;
          background: #f5f5f5;
          border-radius: 20rpx;
          transition: all 0.3s ease;
          
          &.active {
            background: #1890FF;
            
            .filter-text {
              color: #fff;
            }
          }
          
          .filter-text {
            font-size: 24rpx;
            color: #666;
          }
        }
      }
    }
  }
}

.activity-list {
  flex: 1;
  
  .list-content {
    padding: 24rpx 32rpx;
  }
}

.activity-card {
  background: #fff;
  border-radius: 16rpx;
  margin-bottom: 24rpx;
  overflow: hidden;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
  
  .card-header {
    display: flex;
    padding: 24rpx;
    align-items: flex-start;
    
    .activity-image {
      width: 120rpx;
      height: 120rpx;
      border-radius: 12rpx;
      margin-right: 24rpx;
      flex-shrink: 0;
    }
    
    .activity-info {
      flex: 1;
      
      .activity-name {
        font-size: 32rpx;
        font-weight: 600;
        color: #333;
        display: block;
        margin-bottom: 8rpx;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
      
      .activity-desc {
        font-size: 24rpx;
        color: #666;
        display: block;
        margin-bottom: 12rpx;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
      
      .price-info {
        display: flex;
        align-items: center;
        gap: 16rpx;
        
        .original-price {
          font-size: 24rpx;
          color: #999;
          text-decoration: line-through;
        }
        
        .group-price {
          font-size: 28rpx;
          font-weight: 600;
          color: #FF4D4F;
        }
      }
    }
    
    .activity-status {
      flex-shrink: 0;
    }
  }
  
  .card-body {
    padding: 0 24rpx 24rpx;
    
    .activity-meta {
      display: flex;
      gap: 24rpx;
      margin-bottom: 16rpx;
      
      .meta-item {
        display: flex;
        align-items: center;
        gap: 8rpx;
        
        .meta-text {
          font-size: 22rpx;
          color: #999;
        }
      }
    }
    
    .time-info {
      .time-label {
        font-size: 22rpx;
        color: #999;
      }
      
      .time-text {
        font-size: 22rpx;
        color: #666;
      }
    }
  }
  
  .card-actions {
    display: flex;
    border-top: 1rpx solid #f0f0f0;
    
    .action-btn {
      flex: 1;
      display: flex;
      align-items: center;
      justify-content: center;
      gap: 8rpx;
      padding: 20rpx 12rpx;
      background: none;
      border: none;
      font-size: 24rpx;
      border-right: 1rpx solid #f0f0f0;
      
      &:last-child {
        border-right: none;
      }
      
      &.secondary {
        color: #666;
      }
      
      &.primary {
        color: #1890FF;
      }
      
      &.success {
        color: #52C41A;
      }
      
      &.warning {
        color: #FAAD14;
      }
      
      &.danger {
        color: #FF4D4F;
      }
      
      &:active {
        background: #f5f5f5;
      }
    }
  }
}

.load-more {
  padding: 32rpx 0;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 120rpx 0;
  
  .empty-image {
    width: 200rpx;
    height: 200rpx;
    margin-bottom: 32rpx;
  }
  
  .empty-text {
    font-size: 28rpx;
    color: #999;
    margin-bottom: 32rpx;
  }
  
  .empty-btn {
    background: #1890FF;
    color: #fff;
    border: none;
    border-radius: 24rpx;
    padding: 16rpx 32rpx;
    font-size: 26rpx;
  }
}

.fab {
  position: fixed;
  right: 32rpx;
  bottom: 120rpx;
  width: 112rpx;
  height: 112rpx;
  background: #1890FF;
  border-radius: 56rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 8rpx 24rpx rgba(24, 144, 255, 0.3);
  z-index: 999;
  
  &:active {
    transform: scale(0.95);
  }
}
</style>